# -*- coding: utf-8 -*-
import frappe
from frappe.model.document import Document

class ScrapReceiptItem(Document):
    """
    余料入库单子表控制器类
    管理入库单中的余料项信息
    """
    
    def validate(self):
        """验证数据有效性"""
        self.validate_scrap_material()
        self.validate_location()
        self.validate_quantity()
    
    def validate_scrap_material(self):
        """验证余料有效性"""
        if self.scrap_material:
            # 检查余料是否存在
            if not frappe.db.exists("Scrap Material", self.scrap_material):
                frappe.throw(f"余料 {self.scrap_material} 不存在")
            
            # 获取余料信息并填充字段
            material_doc = frappe.get_doc("Scrap Material", self.scrap_material)
            self.material_type = material_doc.material_type
            self.material_name = material_doc.material_name
            self.color_pattern = material_doc.color_pattern
            self.length = material_doc.length
            self.width = material_doc.width
            self.thickness = material_doc.thickness
            self.unit = material_doc.unit
    
    def validate_location(self):
        """验证库位有效性"""
        if self.location:
            # 检查库位是否存在
            if not frappe.db.exists("Scrap Location", self.location):
                frappe.throw(f"库位 {self.location} 不存在")
            
            # 检查库位是否属于入库单的仓库
            receipt_doc = frappe.get_doc(self.parenttype, self.parentname)
            location_doc = frappe.get_doc("Scrap Location", self.location)
            
            if location_doc.warehouse != receipt_doc.warehouse:
                frappe.throw(f"库位 {self.location} 不属于仓库 {receipt_doc.warehouse}")
            
            # 检查库位状态
            if location_doc.status != "启用":
                frappe.throw(f"库位 {self.location} 未启用，无法存放余料")
    
    def validate_quantity(self):
        """验证数量"""
        if self.quantity <= 0:
            frappe.throw("数量必须大于0")
        
        # 检查余料数量是否足够
        if self.scrap_material:
            material_doc = frappe.get_doc("Scrap Material", self.scrap_material)
            if self.quantity > material_doc.quantity:
                frappe.throw(f"余料数量不足，当前库存: {material_doc.quantity}，入库数量: {self.quantity}")